/*
 * modbus_host.h
 *
 *  Created on: Feb 17, 2022
 *      Author: yjs
 */

#ifndef MODBUS_HOST_H_
#define MODBUS_HOST_H_
#include "main.h"
#include "usart.h"
/********************************************************************/
#define MB_RETRY		2
#define MB_NEXT			200
#define MB_DELAY		200
typedef enum {
    MB_OK = 0, MB_ERR, MB_NOACK, MB_NONE,
} mb_state;
struct modbus {
    uint16_t addr;
    uint16_t reg;
    uint8_t num;

    mb_state state;
    uint16_t reg_value1;
    uint16_t reg_value2;
};

void Modbus_HostIni(void);
void Modbus_HostRead(void);


/* 01H 读强制单线圈 */
/* 05H 写强制单线圈 */
#define Slave_REG_D01		0x1000
#define Slave_REG_D02		0x1001
#define Slave_REG_D03		0x1002
#define Slave_REG_D04		0x1003
#define Slave_REG_DXX 		Slave_REG_D04

/* 02H 读取输入状态 */
#define Slave_REG_T01		0x1100
#define Slave_REG_T02		0x1101
#define Slave_REG_T03		0x1102
#define Slave_REG_T04		0x1103
#define Slave_REG_TXX		Slave_REG_T04

/* 03H 读保持寄存器 */
/* 06H 写保持寄存器 */
/* 10H 写多个保存寄存器 */
#define Slave_REG_P01		0x0001
#define Slave_REG_P02		0x0002
#define Slave_REG_P03		0x0003
#define Slave_REG_P04		0x0004
#define Slave_REG_PXX 		Slave_REG_P04

/* 04H 读取输入寄存器(模拟信号) */
#define Slave_REG_A01		0x2001
#define Slave_REG_A02		0x2002
#define Slave_REG_A03		0x2003
#define Slave_REG_A04		0x2004
#define Slave_REG_AXX		REG_A04

/********************************************************************/
#define H_RX_BUF_SIZE		64
#define H_TX_BUF_SIZE      	128

typedef struct {
    uint8_t RxBuf[H_RX_BUF_SIZE];
    uint8_t RxCount;
    uint8_t RxStatus;
    uint8_t RxNewFlag;

    uint8_t RspCode;

    uint8_t TxBuf[H_TX_BUF_SIZE];
    uint8_t TxCount;

    uint16_t Reg01H; /* 保存主机发送的寄存器首地址 */
    uint16_t Reg02H;
    uint16_t Reg03H;
    uint16_t Reg04H;

    uint8_t RegNum; /* 寄存器个数 */

    uint8_t fAck01H; /* 应答命令标志 0 表示执行失败 1表示执行成功 */
    uint8_t fAck02H;
    uint8_t fAck03H;
    uint8_t fAck04H;
    uint8_t fAck05H;
    uint8_t fAck06H;
    uint8_t fAck10H;

} MODH_T;

typedef struct {
    /* 03H 06H 读写保持寄存器 */
    uint16_t P01;
    uint16_t P02;
    uint16_t P03;
    uint16_t P04;
    /* 02H 读写离散输入寄存器 */
    uint16_t T01;
    uint16_t T02;
    uint16_t T03;

    /* 04H 读取模拟量寄存器 */
    uint16_t A01;

    /* 01H 05H 读写单个强制线圈 */
    uint16_t D01;
    uint16_t D02;
    uint16_t D03;
    uint16_t D04;

} VARH_T;

void MODH_Deal(usart_cache* recv);
void MODH_Poll(uint8_t *data, uint16_t len);
void MODH_SendAckWithCRC(void);
void MODH_AnalyzeApp(void);
void MODH_Send03H(uint8_t _addr, uint16_t _reg, uint16_t _num);
void MODH_Read_03H(void);
void MODH_Send06H(uint8_t _addr, uint16_t _reg, uint16_t _value);
void MODH_Read_06H(void);
#endif /* MODBUS_HOST_H_ */
